package com.aries.commons.domains;


import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.CountDownLatch;

/**
 * 服务端响应数据容器
 *
 * @param <R>
 */
public class ServerResponseWrapper<R> {
    @Getter
    @Setter
    private String id;
    private volatile CountDownLatch latch;
    private ObjectDataResponse<R> dataResponse;
    @Setter
    @Getter
    private Integer code;
    @Getter
    @Setter
    //是否数据被取出
    private Boolean got;

    public ServerResponseWrapper(String id) {
        this.id = id;
        this.latch = new CountDownLatch(1);
        this.got = false;
    }

    public Boolean isReady() {

        return this.latch.getCount() == 0;
    }

    public R getResponse() {
        try {
            latch.await();
            if (this.code == 200) {

                return this.dataResponse.getData();
            } else {
                throw new RuntimeException("remote service returned an error!");
            }

        } catch (InterruptedException e) {
            throw new RuntimeException("get rpc response error!", e);
        } finally {
            this.got = true;
        }

    }

    public void countDown(ObjectDataResponse<R> dataResponse, int code) {
        this.latch.countDown();
        this.dataResponse = dataResponse;
        this.code = code;
    }

}
